package com.gexin.weixin.interceptor;

import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.StringUtil;
import com.gexin.weixin.kit.WeXinCacheKeyConst;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

/**
 * 微信TOKEN授权拦截器
 * 2019-09-06  使用方法如下
 * 1.控制器需要继承WxTokenBaseController
 * 2.拦截器用 WexinAuthTokenInterceptor
 */
public class WexinAuthTokenInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation paramInvocation) {
		Controller controller = paramInvocation.getController();
		String wx_token = controller.getHeader("wx_token");
		if (StringUtil.isBlank(wx_token)) {
			wx_token = controller.getPara("wx_token");
		}

		if (StringUtil.isBlank(wx_token)) {
			ApiResponse resp = new ApiResponse();
			resp.setCode(403);
			resp.setMsg("wx_token 没有传递");
			resp.setState(false);
			controller.renderJson(resp);
			return;
		}

		if (!CacheUtils.exists(WeXinCacheKeyConst.wx_token + wx_token)) {
			ApiResponse resp = new ApiResponse();
			resp.setCode(403);
			resp.setMsg("wx_token  无效，请重新授权");
			resp.setState(false);
			controller.renderJson(resp);
			return;
		}
		try {
			controller.setAttr("wx_token",wx_token);
			paramInvocation.invoke();
		} catch (Exception e) {
			e.printStackTrace();
			ApiResponse resp = new ApiResponse();
			resp.setCode(500);
			resp.setMsg("系统异常!");
			resp.setState(false);
			controller.renderJson(resp);
			return;
		}
	}


}
